import { defineStore } from 'pinia';
import { openCommunityInfo } from '@/api/index';
import { IObject } from 'shared/@types/interface';
import { queryCompanyContribute } from '@/api';
import { queryCompanyContribute as queryCompanyContributeWithVersionSelected } from 'shared/api/api-new';
import { ceil } from 'lodash-es';
interface layoutStateTypes {
  rawData: IObject;
  companyData: {
    company_en: string;
    company_zh: string;
    index: number | string;
    contribute: number;
  }[];
  ranking: number | string;
  searchRanking: number;
  totalLength: number;
  total: number;
  companyMaxNum: number;
  companyForm: IObject;
  switchValue: boolean;
  defaultNum: any;
}

export const useCompanyStore = defineStore('company', {
  state: (): layoutStateTypes => ({
    rawData: [],
    companyData: [],
    // 显示排行数
    ranking: 10,
    // 总长度
    totalLength: 0,
    searchRanking: 0,
    // 总和 计算百分比 只有gauss需要
    total: 0,
    // 获取最大值
    companyMaxNum: 0,
    // 筛选参数
    switchValue: true,
    // 默认选中值
    defaultNum: '',
    companyForm: {
      contributeType: 'pr',
      timeRange: 'lastonemonth',
      displayRange: '10',
      version: '',
    },
  }),
  actions: {
    async getCompanyData() {
      let params: object;
      if (this.switchValue) {
        params = {
          community: openCommunityInfo.name,
          contributeType: this.companyForm.contributeType,
          version: this.companyForm.version,
        };
      } else {
        params = {
          community: openCommunityInfo.name,
          contributeType: this.companyForm.contributeType,
          timeRange: this.companyForm.timeRange,
        };
      }
      try {
        const res = await (this.switchValue ? queryCompanyContribute(params) : queryCompanyContributeWithVersionSelected(params));
        if (res.code === 1) {
          const { data } = res;
          this.companyMaxNum = ceil(data[0]?.contribute ?? 0, -2);
          this.rawData = data;

          // 筛选
          if (data[0].company_zh === '个人贡献者') {
            const temp = data[1];
            data[1] = data[0];
            data[0] = temp;
          }
          let index = 1;
          const newData = data
            .filter((i: IObject) => i.contribute > 0)
            .map((i: any) => {
              return {
                ...i,
                index: i.company_zh === '个人贡献者' ? '*' : index++,
              };
            });
          const initVal = 0;
          this.total = newData.reduce((acc: number, cur: IObject) => {
            return acc + cur.contribute;
          }, initVal);
          this.totalLength = newData.length;

          this.ranking = this.companyForm.displayRange === 'all' ? this.totalLength : this.companyForm.displayRange;

          this.companyData = newData.slice(0, this.ranking);
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
});
